<!-- src/views/permissions/CORSSettingsPage.vue -->
<template>
    <div class="cors-settings-page" v-loading="isLoading">
        <el-alert title="功能说明" type="info" show-icon :closable="false" class="page-header-alert">
            <p>
                跨域资源共享（CORS）允许您的静态网站（或其他Web应用）从不同的源访问此存储桶中的资源。您可以在此配置具体的跨域规则。
                <el-link type="primary" href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS"
                    target="_blank">了解更多</el-link>
            </p>
        </el-alert>

        <div class="action-bar">
            <el-button type="primary" :icon="Plus" @click="handleCreateRule">创建规则</el-button>
            <el-button type="danger" :icon="Delete" @click="confirmDeleteAll" :disabled="rules.length === 0">
                删除全部规则
            </el-button>
            <el-button @click="fetchRules" :icon="Refresh" :disabled="isLoading || isSaving">刷新</el-button>
        </div>

        <!-- src/views/permissions/CORSSettingsPage.vue -->

        <el-table :data="rules" style="width: 100%" v-if="rules.length > 0">
            <el-table-column prop="AllowedOrigins" label="来源 (Origins)">
                <template #default="{ row }">
                    <!-- 假设 AllowedOrigins 总是存在且是数组 -->
                    <el-tag v-for="origin in row.AllowedOrigins" :key="origin">{{ origin }}</el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="AllowedMethods" label="允许 Methods">
                <template #default="{ row }">
                    <!-- 假设 AllowedMethods 总是存在且是数组 -->
                    <el-tag v-for="method in row.AllowedMethods" :key="method" type="success">{{ method }}</el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="AllowedHeaders" label="允许 Headers">
                <template #default="{ row }">
                    <!-- 【核心修正1】先判断 row.AllowedHeaders 是否存在 -->
                    <span v-if="row.AllowedHeaders && row.AllowedHeaders.length > 0">{{ row.AllowedHeaders.join(', ')
                        }}</span>
                    <span v-else>-</span>
                </template>
            </el-table-column>

            <!-- 【核心修正2】为 ExposeHeaders 也加上同样的保护 -->
            <el-table-column prop="ExposeHeaders" label="暴露 Headers">
                <template #default="{ row }">
                    <span v-if="row.ExposeHeaders && row.ExposeHeaders.length > 0">{{ row.ExposeHeaders.join(', ')
                        }}</span>
                    <span v-else>-</span>
                </template>
            </el-table-column>

            <el-table-column prop="MaxAgeSeconds" label="缓存时间(秒)" />

            <el-table-column label="操作" width="150">
                <template #default="scope">
                    <el-button link type="primary" size="small"
                        @click="handleEditRule(scope.row, scope.$index)">编辑</el-button>
                    <el-button link type="danger" size="small" @click="removeRule(scope.$index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-empty v-else-if="!isLoading" description="当前未配置任何CORS规则"></el-empty>

        <div class="footer-actions">
            <el-button type="primary" @click="saveRules" :loading="isSaving" :disabled="rules.length === 0">
                保存所有配置
            </el-button>
        </div>

        <!-- 引入我们新的抽屉组件 -->
        <CORSRuleDrawer v-model:visible="isDrawerVisible" :rule-data="currentRule" @submit="handleRuleSubmit" />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete, Refresh } from '@element-plus/icons-vue';
import { api } from '@/api';
// 【重要】导入我们新创建的抽屉组件
import CORSRuleDrawer from '@/components/CORSRuleDrawer.vue';

const route = useRoute();
const bucketName = ref(route.params.bucketName);
const rules = ref([]);
const isLoading = ref(false);
const isSaving = ref(false);

const isDrawerVisible = ref(false);
const currentRule = ref(null);

const fetchRules = async () => {
    isLoading.value = true;
    try {
        const response = await api.cors.getBucketCors(bucketName.value);
        rules.value = response.data.map((rule, index) => ({
            ...rule,
            originalIndex: index,
        }));
        rules.value = response.data;
    } catch (error) {
        ElMessage.error('获取CORS配置失败');
    } finally {
        isLoading.value = false;
    }
};

const handleCreateRule = () => {
    currentRule.value = null; // 传入 null 表示创建
    isDrawerVisible.value = true;
};

const handleEditRule = (rule, index) => {
    // 传入规则数据和它的原始索引，用于后续更新
    currentRule.value = { ...rule, originalIndex: index };
    isDrawerVisible.value = true;
};

const handleRuleSubmit = (submittedRule) => {
    if (submittedRule.originalIndex !== undefined) {
        // 编辑模式：替换掉原来的规则
        const index = submittedRule.originalIndex;
        delete submittedRule.originalIndex; // 清理掉辅助字段
        rules.value.splice(index, 1, submittedRule);
    } else {
        // 创建模式：添加到规则列表
        rules.value.push(submittedRule);
    }
};

const removeRule = (index) => {
    ElMessageBox.confirm(
        '一旦删除该条跨域规则将不可恢复，确定继续吗？',
        '确认删除该条跨域规则？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            icon: 'el-icon-warning-outline', // 使用Element Plus的警告图标
        }
    ).then(() => {
        // 用户点击了“确定”
        rules.value.splice(index, 1);
        ElMessage({
            type: 'success',
            message: '删除成功',
        });
    }).catch(() => {
        // 用户点击了“取消”或关闭了弹窗
        ElMessage({
            type: 'info',
            message: '已取消删除',
        });
    });
};

const saveRules = async () => {
    isSaving.value = true;
    // 提交前，清理掉前端专用的空数组，以匹配后端API要求
    const payload = rules.value.map(rule => {
        const cleanRule = { ...rule };
        if (!cleanRule.AllowedHeaders || !cleanRule.AllowedHeaders[0]) delete cleanRule.AllowedHeaders;
        if (!cleanRule.ExposeHeaders || !cleanRule.ExposeHeaders[0]) delete cleanRule.ExposeHeaders;
        return cleanRule;
    });

    try {
        await api.cors.setBucketCors(bucketName.value, payload);
        ElMessage.success('CORS配置已成功保存');
        fetchRules();
    } catch (error) {
        ElMessage.error(error.response?.data?.error || '保存CORS配置失败');
    } finally {
        isSaving.value = false;
    }
};

const confirmDeleteAll = () => {
    ElMessageBox.confirm('此操作将永久删除此存储桶的所有CORS规则，是否继续？', '警告', { /* ... */ }
    ).then(async () => {
        isSaving.value = true;
        try {
            await api.cors.deleteBucketCors(bucketName.value);
            ElMessage.success('所有CORS规则已删除');
            rules.value = [];
        } catch (error) {
            ElMessage.error('删除CORS配置失败');
        } finally {
            isSaving.value = false;
        }
    }).catch(() => { });
};

onMounted(fetchRules);
</script>

<style scoped>
.cors-settings-page {
    padding: 24px;
}

.page-header-alert {
    margin-bottom: 20px;
}

.action-bar {
    margin-bottom: 20px;
}

.footer-actions {
    margin-top: 20px;
}

.el-tag {
    margin-right: 5px;
}
</style>